package com.xxl.job.executor.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class TaskPoolConfig {

    @Value("${syncTaskExecutor.corePoolSize}")
    private int corePoolSize;
    @Value("${syncTaskExecutor.maxPoolSize}")
    private int maxPoolSize;
    @Value("${syncTaskExecutor.queueCapacity}")
    private int queueCapacity;
    @Value("${syncTaskExecutor.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Bean("syncTaskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//核心线程数目 10
        executor.setMaxPoolSize(maxPoolSize);//指定最大线程数 20
        executor.setQueueCapacity(queueCapacity);//队列中最大的数目  200
        executor.setKeepAliveSeconds(keepAliveSeconds);//线程空闲后的最大存活时间  60
        executor.setThreadNamePrefix("sync-task-");//线程名称前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();

        return executor;
    }

    @Bean("syncBusinessTaskExecutor")
    public Executor syncBusinessTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);//核心线程数目 10
        executor.setMaxPoolSize(maxPoolSize);//指定最大线程数 20
        executor.setQueueCapacity(queueCapacity);//队列中最大的数目  200
        executor.setKeepAliveSeconds(keepAliveSeconds);//线程空闲后的最大存活时间  60
        executor.setThreadNamePrefix("sync-business-task-");//线程名称前缀
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
